package com.wangsh.projDemo.system.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wangsh.projDemo.common.pojo.ApiResponse;
import com.wangsh.projDemo.common.pojo.ApiResponseEnum;
import com.wangsh.projDemo.common.pojo.JSONEnum;
import com.wangsh.projDemo.common.service.BaseServiceImpl;
import com.wangsh.projDemo.common.util.ConstatFinalUtil;
import com.wangsh.projDemo.common.util.PageInfoUtil;
import com.wangsh.projDemo.system.dao.IASysFileDao;
import com.wangsh.projDemo.system.dao.IASysProDao;
import com.wangsh.projDemo.system.pojo.ASysFile;
import com.wangsh.projDemo.system.pojo.ASysFileEnum;
import com.wangsh.projDemo.system.pojo.ASysPro;
import com.wangsh.projDemo.system.pojo.ASysProEnum;
import com.wangsh.projDemo.system.service.ISystemService;

/**
 * Service实现类(系统模块)
 *
 * @author TeaBig
 */
@Service("systemService")
public class SystemServiceImpl extends BaseServiceImpl implements ISystemService
{
	@Resource
	private IASysFileDao sysFileDao;
	@Resource
	private IASysProDao sysProDao;

	/**
	 * 初始化操作
	 */
	@PostConstruct
	public ApiResponse<Object> reloadSystem()
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		/* 查询所有启用的共享变量,系统配置 */
		Map<String, Object> condMap = new HashMap<String, Object>();
		condMap.put("status", ASysProEnum.STATUS_ENABLE.getStatus());
		ApiResponse<ASysPro> response = this.findCondListSysProService(null, condMap);
		List<ASysPro> sysProList = response.getDataListJava();
		/* 循环放到Map中 */
		for (Iterator iterator = sysProList.iterator(); iterator.hasNext();)
		{
			ASysPro sysPro = (ASysPro) iterator.next();
			ConstatFinalUtil.SYS_PRO_MAP.put(sysPro.getEngName(), sysPro);
		}
		ConstatFinalUtil.SYS_LOGGER.info("==初始化完成==变量:{}", ConstatFinalUtil.SYS_PRO_MAP);
		apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> saveOneSysFileService(ASysFile sysFile)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();

		sysFile.setCreateTime(new Date());
		sysFile.setUpdateTime(new Date());
		int res = this.sysFileDao.save(sysFile);
		if (res > 0)
		{
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			dataMap.put(JSONEnum.ID.getName(), sysFile.getId());
			dataMap.put(ApiResponseEnum.NAME_ONE.getName(), sysFile);
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else
		{
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	public ApiResponse<Object> updateOneSysFileService(ASysFile sysFile)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		sysFile.setUpdateTime(new Date());
		int res = this.sysFileDao.update(sysFile);
		if (res > 0)
		{
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			dataMap.put(JSONEnum.ID.getName(), sysFile.getId());
			dataMap.put(ApiResponseEnum.NAME_ONE.getName(), sysFile);
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else
		{
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> updateOneSysFileService(ASysFile sysFile, Map<String, Object> paramsMap) throws Exception
	{
		if (paramsMap.size() == 0)
		{
			return this.updateOneSysFileService(sysFile);
		}

		ApiResponse<Object> apiResponse = new ApiResponse<Object>();

		try
		{
			String fileName = paramsMap.get("fileName") + "";
			InputStream is = (InputStream) paramsMap.get("inputStream");
			String fileSize = paramsMap.get("fileSize") + "";

			/* 上传文件的相对路径 */
			String uploadFile = ConstatFinalUtil.CONFIG_JSON.getString("website.uploadFile");
			/* 存储的是网址的绝对路径 */
			String souPath = sysFile.getFilePath();
			/* 真实路径 */
			String truePath = ConstatFinalUtil.CONFIG_JSON.getString("website.truePath");
			String midPath = "sysFile";
			if (sysFile.getFileRelaType() == ASysFileEnum.FILERELATYPE_USERSCATE.getStatus())
			{
				/* 读取usersCate的系统变量 */
				ASysPro usersCateSys = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("uploadPath_cate");
				midPath = usersCateSys.getVals();
			} else
			{
				ASysPro usersCateSys = (ASysPro) ConstatFinalUtil.SYS_PRO_MAP.get("uploadPath_facebook_users");
				midPath = usersCateSys.getVals();
			}
			/*
			 * 网站的相对路径, 路径是写活的
			 * 网站的相对路径, * 路径是写活的
			 */
			String tarRelaPath = uploadFile + "/" + midPath + "/" + this.dateFormatUtil.dateStr(new Date()) + "/"
					+ UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."), fileName.length());
			File tarTrueFile = new File(truePath + tarRelaPath);

			/* 创建父目录 */
			if (!tarTrueFile.getParentFile().exists())
			{
				tarTrueFile.getParentFile().mkdirs();
			}
			sysFile.setName(fileName);
			sysFile.setFileSize(fileSize);
			sysFile.setFilePath(tarRelaPath);

			FileOutputStream fos = new FileOutputStream(tarTrueFile);
			/* 复制文件 */
			boolean flag = this.fileUtil.copyFile(is, fos);
			if (flag)
			{
//				/* 对上传文件进行处理 */
//				if (sysFile.getFileRelaType() == ASysFileEnum.FILERELATYPE_FB_USERS.getStatus())
//				{
//					FileInputStream fis = new FileInputStream(tarTrueFile);
//					List<Map<String, Object>> dataList = this.poiUtil.readExcel(fis, "xlsx");
//					/* facebook用户上传处理 */
//					ApiResponse<Object> apiResponseDb = this.ordersOperService.batchOrdersUsersService(dataList);
//					ConstatFinalUtil.SYS_LOGGER.info("批量导入订单用户信息:{}", apiResponseDb.toJSON().toJSONString());
//				}

				if (souPath != null && !"".equalsIgnoreCase(souPath))
				{
					/* 相对路径 */
					File souFile = new File(truePath + souPath);
					if (!souFile.delete())
					{
						ConstatFinalUtil.SYS_LOGGER.error("删除原始文件失败:原始文件路径:{}", souFile.getAbsolutePath());
					}
				}
			}

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
			/* 更新记录 */
			this.updateOneSysFileService(sysFile);
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("上传头像失败了,id:{}", sysFile.getId(), e);
			throw e;
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> deleteOneSysFileService(Map<String, Object> condMap)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		int res = this.sysFileDao.delete(condMap);
		if (res > 0)
		{
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else
		{
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<ASysFile> findCondListSysFileService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{
		ApiResponse<ASysFile> apiResponse = new ApiResponse<ASysFile>();
		apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		List<ASysFile> sysFileList = Collections.EMPTY_LIST;

		Map<String, List<ASysFile>> dataList = new HashMap<String, List<ASysFile>>();
		/* 对关键字进行模糊匹配 */
		if (condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
		{
			condMap.put("keyword", "%" + condMap.get("keyword") + "%");
		}

		/* 设置分页相关信息 */
		if (pageInfoUtil != null)
		{
			/* 设置分页信息 */
			Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
			sysFileList = this.sysFileDao.findList(condMap);
			pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
			/* 向接口中放分页信息 */
			apiResponse.setPageInfoUtil(pageInfoUtil);
		} else
		{
			sysFileList = this.sysFileDao.findList(condMap);
		}
		/* 将结果放到JSON中 */
		dataList.put(ApiResponseEnum.NAME_LIST.getName(), sysFileList);

		apiResponse.setDataListJava(sysFileList);
		apiResponse.setDataList(dataList);
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<ASysFile> findOneSysFileService(Map<String, Object> condMap)
	{
		ApiResponse<ASysFile> apiResponse = new ApiResponse<ASysFile>();

		Map<String, ASysFile> data = new HashMap<String, ASysFile>();
		ASysFile sysFile = this.sysFileDao.findOne(condMap);
		data.put(ApiResponseEnum.NAME_ONE.getName(), sysFile);
		apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		/* 将结果放到JSON中 */
		apiResponse.setDataOne(data);
		apiResponse.setDataOneJava(sysFile);
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	/* 系统配置操作开始 */
	@Override
	public ApiResponse<Object> saveOneSysProService(ASysPro sysPro)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		sysPro.setCreateTime(new Date());
		sysPro.setUpdateTime(new Date());
		int res = this.sysProDao.save(sysPro);
		if (res > 0)
		{
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			dataMap.put(JSONEnum.ID.getName(), sysPro.getId());
			dataMap.put(ApiResponseEnum.NAME_ONE.getName(), sysPro);
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else
		{
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> updateOneSysProService(ASysPro sysPro)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();

		int res = this.sysProDao.update(sysPro);
		if (res > 0)
		{
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			dataMap.put(JSONEnum.ID.getName(), sysPro.getId());
			dataMap.put(ApiResponseEnum.NAME_ONE.getName(), sysPro);
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else
		{
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<Object> deleteOneSysProService(Map<String, Object> condMap)
	{
		ApiResponse<Object> apiResponse = new ApiResponse<Object>();
		int res = this.sysProDao.delete(condMap);
		if (res > 0)
		{
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put(JSONEnum.EFFECT.getName(), res);
			apiResponse.setDataOne(dataMap);

			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		} else
		{
			apiResponse.setCode(ApiResponseEnum.STATUS_FAILED.getStatus());
		}
		apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), Collections.EMPTY_MAP);
		return apiResponse;
	}

	@Override
	public ApiResponse<ASysPro> findCondListSysProService(PageInfoUtil pageInfoUtil, Map<String, Object> condMap)
	{
		ApiResponse<ASysPro> apiResponse = new ApiResponse<ASysPro>();
		apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
		List<ASysPro> SysProList = Collections.EMPTY_LIST;

		Map<String, List<ASysPro>> dataList = new HashMap<String, List<ASysPro>>();
		try
		{

			/* 对关键字进行模糊匹配 */
			if (condMap.get("keyword") != null && !"".equalsIgnoreCase(condMap.get("keyword") + ""))
			{
				condMap.put("keyword", "%" + condMap.get("keyword") + "%");
			}

			/* 设置分页相关信息 */
			if (pageInfoUtil != null)
			{
				/* 设置分页信息 */
				Page page = PageHelper.startPage(pageInfoUtil.getCurrentPage(), pageInfoUtil.getPageSize());
				SysProList = this.sysProDao.findList(condMap);
				pageInfoUtil.setTotalRecord(Integer.valueOf(page.getTotal() + ""));
				/* 向接口中放分页信息 */
				apiResponse.setPageInfoUtil(pageInfoUtil);
			} else
			{
				SysProList = this.sysProDao.findList(condMap);
			}
			/* 将结果放到JSON中 */
			dataList.put(ApiResponseEnum.NAME_LIST.getName(), SysProList);

			apiResponse.setDataListJava(SysProList);
			apiResponse.setDataList(dataList);
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
					Collections.EMPTY_MAP);
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("查询多条记录失败了", e);
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), infoMap);
		}
		return apiResponse;
	}

	@Override
	public ApiResponse<ASysPro> findOneSysProService(Map<String, Object> condMap)
	{
		ApiResponse<ASysPro> apiResponse = new ApiResponse<ASysPro>();

		Map<String, ASysPro> data = new HashMap<String, ASysPro>();
		try
		{
			ASysPro SysPro = this.sysProDao.findOne(condMap);
			data.put(ApiResponseEnum.NAME_ONE.getName(), SysPro);
			apiResponse.setCode(ApiResponseEnum.STATUS_SUCCESS.getStatus());
			/* 将结果放到JSON中 */
			apiResponse.setDataOne(data);
			apiResponse.setDataOneJava(SysPro);
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""),
					Collections.EMPTY_MAP);
		} catch (Exception e)
		{
			ConstatFinalUtil.SYS_LOGGER.error("查询一条记录失败了", e);
			apiResponse.setCode(ApiResponseEnum.STATUS_SERVER_ERROR.getStatus());
			Map<String, String> infoMap = new HashMap<String, String>();
			/* 报错信息的占位符 */
			infoMap.put("errinfo", e.toString());
			apiResponse.setInfo(ConstatFinalUtil.INFO_JSON.getString(apiResponse.getCode() + ""), infoMap);
		}
		return apiResponse;
	}
}
